<?php

namespace Trois\Crontab;

use App\Model\OceAdvertiserReportCityModel;
use App\Model\OceAdvertiserReportModel;
use App\Model\OceCrontabLogModel;
use EasySwoole\Component\Singleton;
use EasySwoole\Crontab\JobInterface;
use EasySwoole\EasySwoole\Core;
use EasySwoole\EasySwoole\Logger;
use Trois\Lib\Help;

/**
 * 清除过期数据
 */
class FlushDbCrontab implements JobInterface
{
    use Singleton;

    private array $models = [
        [
            'class' => OceAdvertiserReportCityModel::class,
            'field' => 'datetime',
            'days' => -7,
        ],

        [
            'class' => OceAdvertiserReportModel::class,
            'field' => 'datetime',
            'days' => -7,
        ],
        [
            'class' => OceCrontabLogModel::class,
            'field' => 'create_time',
            'days' => -7,
        ],
    ];

    public function jobName(): string
    {
        return "FlushDbCrontab";
    }

    public function crontabRule(): string
    {
        if (Core::getInstance()->runMode() === 'dev') {
            return '*/1 * * * *';
        }

        return '0 5 * * *';
    }

    public function run(): void
    {
        $this->handle();
    }

    private function handle()
    {
        Logger::getInstance()->info("开始处理 FlushDbCrontab");

        foreach ($this->models as $currentModel) {
            \co::sleep(20);
            Help::modelInvoke($currentModel['class'], function ($model) use ($currentModel) {
                $model->destroy([$currentModel['field'] => [strtotime(date("Y-m-d", strtotime($currentModel['days'] . " day"))), '<']]);
            });
        }

        Logger::getInstance()->info("开始处理成功 FlushDbCrontab");
    }

    public function onException(\Throwable $throwable)
    {
        Logger::getInstance()->error("FlushDbCrontab onException:" + $throwable->getMessage());
    }

}